package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// CleaningSetting 保洁配置模型
type CleaningSetting struct {
	BaseModel
	StoreId             int64  `orm:"column(store_id)" json:"store_id"`         // 门店ID
	Enabled             bool   `orm:"default(false)" json:"enabled"`            // 是否启用保洁功能
	CleaningTimeSlots   string `orm:"type(text)" json:"cleaning_time_slots"`    // 保洁时段，JSON格式存储，例如：[{"start":"09:00","end":"12:00"}]
	ReservedMinutes     int    `orm:"default(30)" json:"reserved_minutes"`      // 预留保洁时间（分钟）
	AutoAssign          bool   `orm:"default(true)" json:"auto_assign"`         // 是否自动分配保洁任务
	NotifyBeforeMinutes int    `orm:"default(15)" json:"notify_before_minutes"` // 保洁开始前多少分钟通知保洁人员
	Store               *Store `orm:"-" json:"store,omitempty"`
}

// TableName 设置表名
func (cs *CleaningSetting) TableName() string {
	return "ss_cleaning_setting"
}

// GetCleaningSettingByStoreId 根据门店ID获取保洁配置
func GetCleaningSettingByStoreId(storeId int64) (*CleaningSetting, error) {
	o := orm.NewOrm()
	setting := &CleaningSetting{StoreId: storeId}
	err := o.Read(setting, "StoreId")
	if err == orm.ErrNoRows {
		// 如果没有找到特定门店的配置，返回默认配置
		return &CleaningSetting{
			StoreId:             storeId,
			Enabled:             false,
			CleaningTimeSlots:   "[]",
			ReservedMinutes:     30,
			AutoAssign:          true,
			NotifyBeforeMinutes: 15,
		}, nil
	}
	return setting, err
}

// GetAllCleaningSettings 获取所有保洁配置
func GetAllCleaningSettings() ([]CleaningSetting, error) {
	o := orm.NewOrm()
	var settings []CleaningSetting
	_, err := o.QueryTable(new(CleaningSetting)).All(&settings)
	return settings, err
}

// GetCleaningSettingsByFranchiseId 根据加盟商ID获取保洁配置列表
func GetCleaningSettingsByFranchiseId(franchiseId int64) ([]CleaningSetting, error) {
	o := orm.NewOrm()
	var settings []CleaningSetting
	// 首先获取加盟商的所有门店
	var stores []Store
	_, err := o.QueryTable(new(Store)).Filter("franchise_id", franchiseId).All(&stores)
	if err != nil {
		return nil, err
	}

	if len(stores) == 0 {
		return settings, nil // 没有门店，返回空列表
	}

	// 获取门店ID列表
	var storeIDs []int64
	for _, store := range stores {
		storeIDs = append(storeIDs, store.Id)
	}

	// 获取这些门店的所有保洁配置
	_, err = o.QueryTable(new(CleaningSetting)).Filter("store_id__in", storeIDs).All(&settings)
	return settings, err
}

// GetCleaningSettings 获取保洁配置列表
func GetCleaningSettings(page, pageSize int, storeId int64) ([]*CleaningSetting, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(CleaningSetting))

	if storeId != 0 {
		qs = qs.Filter("store_id", storeId)
	}

	var settings []*CleaningSetting
	count, err := qs.Count()
	if err != nil {
		return nil, 0, err
	}

	_, err = qs.Limit(pageSize, (page-1)*pageSize).All(&settings)
	if err != nil {
		return nil, 0, err
	}

	// 获取门店信息
	storeIDs := make([]int64, 0)
	for _, setting := range settings {
		storeIDs = append(storeIDs, setting.StoreId)
	}

	if len(storeIDs) > 0 {
		var stores []Store
		_, err := o.QueryTable(new(Store)).Filter("id__in", storeIDs).All(&stores)
		if err == nil {
			storeMap := make(map[int64]*Store)
			for i := range stores {
				storeMap[stores[i].Id] = &stores[i]
			}
			for _, setting := range settings {
				if store, ok := storeMap[setting.StoreId]; ok {
					setting.Store = store
				}
			}
		}
	}

	return settings, count, nil
}

func GetCleaningSettingById(id int64) (*CleaningSetting, error) {
	o := orm.NewOrm()
	setting := &CleaningSetting{BaseModel: BaseModel{Id: id}}
	err := o.Read(setting)
	return setting, err
}

// CreateOrUpdateCleaningSetting 创建或更新保洁配置
func CreateOrUpdateCleaningSetting(setting *CleaningSetting) (int64, error) {
	o := orm.NewOrm()
	if setting.Id > 0 {
		_, err := o.Update(setting)
		return setting.Id, err
	}
	id, err := o.Insert(setting)
	return id, err
}

// DeleteCleaningSetting 删除保洁配置
func DeleteCleaningSetting(id int64) error {
	o := orm.NewOrm()
	_, err := o.QueryTable(new(CleaningSetting)).Filter("id", id).Delete()
	return err
}
